// pages/basepreview/basepreview.js

/**
 * 显示未签名的货单
 */
const app = getApp()
const httpsUrl = app.httpsPrefix;

const {$Message} = require('../../dist/base/index');
const {$Toast} = require('../../dist/base/index');

Page({

    /**
     * 页面的初始数据，showView用来控制下面的按钮的显示
     */
    data: {
        imgUrl: "", showView: false, attendSuccessImg: "", canvasImgUrl: "", modal1: false
    },

    /**
     * 取消按钮
     */
    cancel() {
        wx.navigateBack({
            delta: 1
        })
    },
    /**
     * 打开相机，拍照/选图上传
     */
    openCamera() {
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
                wx.showModal({
                    title: "提示",
                    showCancel: true,
                    content: "您确认上传此货单图片到服务器么？",
                    success: (re) => {
                        if (re.confirm) {
                            this.confirmUpload(res);
                        }
                    }
                })
            }
        })
    },
    confirmUpload(res) {

        //压缩图片
        var tempFilePaths = res.tempFilePaths;

        this.setData({
            attendSuccessImg: tempFilePaths[0]
        });

        let model = "";
        wx.getSystemInfo({
            success: function (res) {
                model = res.model;
            }
        })
        if (model.indexOf("iPhone") <= 0) {
            this.uploadFileOpt(this.data.attendSuccessImg);
        } else {
            drawCanvas();
        }
    },
    // 缩放图片
    drawCanvas() {
        const ctx = wx.createCanvasContext('attendCanvasId');
        ctx.drawImage(tempFilePaths[0], 0, 0, 94, 96);
        ctx.draw();
        that.prodImageOpt();
    },
    // 生成图片
    prodImageOpt: function () {
        var that = this;
        wx.canvasToTempFilePath({
            canvasId: 'attendCanvasId',
            success: function success(res) {
                this.setData({
                    canvasImgUrl: res.tempFilePath
                });
                // 上传图片
                that.uploadFileOpt(this.data.canvasImgUrl);
            },
            complete: function complete(e) {
            }
        });
    },

    uploadFileOpt: function (path) {

        this.doUploadLocalPic(path)
    },

    /**
     * 界面显示后，根据上个界面中存储在本地的order发送请求，
     * 获取未签名货单的base64，并显示
     */
    onLoad: function (options) {
        $Toast({
            mask: false,
            content: '正在初始化货单...',
            type: 'loading'
        });
        this.initNoSignedOrder()
    },

    doUploadLocalPic(path) {

        $Toast({
            mask: false,
            content: '正在初始化货单...',
            type: 'loading'
        });
        let order = wx.getStorageSync("order")

        let account = wx.getStorageSync("username")

        var timestamp2 = (new Date()).valueOf();

        wx.uploadFile({
            url: httpsUrl, //接口地址
            filePath: path,
            name: 'file',
            formData: {
                //HTTP 请求中其他额外的 form data
                account: account,
                query: 'mp_uploadhecheng',
                单号: order,
                compress_name: 'camera_' + account + '_' + order + '_' + timestamp2+'.png',
                compress_path: 'mp_hecheng'
            },
            success: function ({data}) {
                console.log(data)
                data = JSON.parse(data)

                $Toast.hide()

                let flag = data.flag
                let message = data.message;

                wx.showModal({
                    title: "提示",
                    showCancel: false,
                    content: message,
                    success: (res) => {
                        wx.navigateBack({
                            delta: 1
                        })
                    }
                })

            },
            fail: function () {
                $Toast.hide()
            }
        });
    },
    backMain() {
        this.setData({modal1: false})
        wx.navigateBack({
            delta: 1
        })
    },

    //初始化货单
    initNoSignedOrder() {
        let order = wx.getStorageSync("order")
        // order = "XWS170526007";

        if (order.indexOf("=") != -1) {
            order = order.split("=")[1]
        }
        let account = wx.getStorageSync("username")

        var m = {query: 'mp_scan', order: order, username: account }
        wx.request({
            url: httpsUrl, data: m,
            success: ({data}) => {
                let message = data["message"]

                let flag = data["flag"]
                //扫码成功标志为1，其他的都小程序弹出提示
                if (flag === "1") {
                    data = data.data[0].data
                    var array = wx.base64ToArrayBuffer(data);
                    var base64 = wx.arrayBufferToBase64(array);
                    this.setData({ imgurl: "data:image/png;base64," + base64,showView:true });
                    $Toast.hide()

                    return
                } else {
                    $Toast.hide()

                    if (message === 'null') {
                        this.setData({modal1: true})
                        return
                    }
                    $Toast({
                        content: message,
                        type: 'error'
                    });
                }

            },
            fail: function () {
                wx.hideToast()

                log.showModel({
                    msg: "网络错误", success: () => {
                        wx.navigateBack({
                            delta: 1
                        })
                    }
                })
            }
        })
    },
    navToSign: function () {
        wx.navigateTo({
            url: '../handWriting/handWriting'
        })
    }
    ,
    showPreview: function () {
        wx.previewImage({
            current: this.data.imgurl, // 当前显示图片的http链接
            urls: [this.data.imgurl] // 需要预览的图片http链接列表
        })
    }
})
